package com.xiaoye.qbproject.handle;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoye.qbproject.domain.wiki.ContentInfo;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//@Component
public class ContentInfoToStringTypeHandler extends BaseTypeHandler<ContentInfo> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 允许反序列化未知字段（避免字段不匹配报错）
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 序列化时包含空字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, ContentInfo parameter, JdbcType jdbcType) throws SQLException {
        try {
            // 序列化整个 ContentInfo 对象（包含 infoboxTable）
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (JsonProcessingException e) {
            throw new SQLException("序列化 ContentInfo 失败", e);
        }
    }

    @Override
    public ContentInfo getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJson(json);
    }

    @Override
    public ContentInfo getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJson(json);
    }

    @Override
    public ContentInfo getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJson(json);
    }

    private ContentInfo parseJson(String json) {
        try {
            if (json == null || json.isEmpty()) {
                return null;
            }
            // 使用 TypeReference 保留泛型信息
            return objectMapper.readValue(json, new TypeReference<ContentInfo>() {
            });
        } catch (Exception e) {
            throw new RuntimeException("反序列化 ContentInfo 失败", e);
        }
    }

}